using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;

namespace LocalizeMe.Sources
{
    public partial class SourceDesigner : Form
    {
        public SourceDesigner()
        {
            InitializeComponent();
        }

        private ResourceSource _source;

        public ResourceSource Source
        {
            get
            {
                return _source;
            }
        }

        public SourceDesigner(ResourceSource source):this()
        {
            this._source = source;
            this.propertyGrid1.SelectedObject = this._source;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void SourceDesigner_Load(object sender, EventArgs e)
        {
            FillSources();
        }

        private Dictionary<string,Type> _sources;

        private void FillSources()
        {
            this.cmbSources.Items.Clear();

            string path = this.GetType().Assembly.Location;
            if (File.Exists(path))
            {
                FileInfo fi = new FileInfo(path);
                string[] files = Directory.GetFiles(fi.DirectoryName, "*.dll");
                foreach (string file in files)
                {
                    Assembly ass = Assembly.LoadFile(file);
                    foreach (Type type in ass.GetTypes())
                    {
                        if (type.IsSubclassOf(typeof(ResourceSource)))
                        {
                            if (_sources == null)
                                _sources = new Dictionary<string, Type>();
                            _sources.Add(type.FullName, type); 

                            this.cmbSources.Items.Add(type.FullName);
                        }
                    }
                }
            }
        }

        private void cmbSources_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbSources.SelectedItem != null)
            {
                if (_sources.ContainsKey(cmbSources.SelectedItem.ToString()))
                {
                    _source = (ResourceSource)_sources[cmbSources.SelectedItem.ToString()].InvokeMember("new", BindingFlags.CreateInstance, null, null, new object[0]);
                    this.propertyGrid1.SelectedObject = _source;
                }
            }
        }


    }
}